package com.tron.sync.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tron.sync.commons.TronUtils;
import com.tron.sync.entities.JZOrg;
import com.tron.sync.entities.OAOrg;
import com.tron.sync.mapper.JZOrgMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class JZOrgServiceImpl extends ServiceImpl<JZOrgMapper, JZOrg> implements JZOrgService {
    @Value("${levelId1}")
    private String levelId1;

    @Value("${region1}")
    private String region1;


    @Autowired
    private SyndaServiceImpl syndaService;

    @Override
    public JZOrg getByName(String name) {
        JZOrg jzOrg = this.baseMapper.selectOne(Wrappers.<JZOrg>lambdaQuery().eq(JZOrg::getName, name));
        return jzOrg;
    }

    /**
     * 获取机构下面的子机构
     * @param name
     * @return
     */
    @Override
    public List<JZOrg> getByLikeName(String name) {
        // aaa% 以aaa 开头 但是不等于 aaa 的数据
        List<JZOrg> jzOrgs = this.baseMapper.selectList(Wrappers.<JZOrg>lambdaQuery().likeRight(JZOrg::getName, name).ne(JZOrg::getName, name));
        return jzOrgs;
    }

    public void saveOrg(String zzjgYwxt,String parentId,String parentName){
        //查询第一级
        QueryWrapper<JZOrg> jzOrgQueryWrapper = new QueryWrapper<>();
        jzOrgQueryWrapper.eq("jigdm",zzjgYwxt);
        List<JZOrg> listOrg = this.list(jzOrgQueryWrapper);
        System.out.println(listOrg.isEmpty());
        if (listOrg.size()>0) {
            listOrg.forEach(o->{
                OAOrg oaOrg = new OAOrg();
                oaOrg.setSort(1);
                oaOrg.setParentId(parentId);
                oaOrg.setName(o.getZzjgZw());
                oaOrg.setOrgAlias(TronUtils.getPinYinHeadChar(o.getZzjgZw()));
                oaOrg.setBrevity(o.getZzjgZw());
                oaOrg.setLevelID(levelId1);
                oaOrg.setRegion(region1);
                oaOrg.setStatus("actived");
                oaOrg.setOrgType("1");
                oaOrg.setInherit("0");
                oaOrg.setOrgCode(TronUtils.getUUID());
                oaOrg.setPathName(o.getZzjgZw());
                String id = syndaService.saveOrg(oaOrg);
                if (!StringUtils.isEmpty(id)){
                    o.setSyndaId(id);
                    this.updateById(o);
                }
                saveOrg(o.getZzjgYwxt(),id,o.getZzjgZw());
            });
        }
    }
}
